<template>
  <el-form
    ref="previewForm"
    class="process-form"
    label-width="auto"
    :label-position="labelPosition"
    :rules="rules"
    :model="_value"
  >
    <template v-for="(item, index) in forms" :key="item.name + index">
      <el-form-item :prop="item.id" :label="item.title">
        <template #label>
          <span>{{ item.title }}</span>
          <div v-show="item.props.showDescription">
            <el-tooltip :content="item.props.description" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <form-design-render :ref="`sub-item_${item.id}`" v-model="_value[item.id]" mode="PC" :config="item" />
      </el-form-item>
    </template>
  </el-form>
</template>

<script setup>
import { computed, ref, getCurrentInstance, nextTick } from "vue";
import FormDesignRender from "./FormDesignRender";

const props = defineProps({
  forms: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Object,
    default: () => ({})
  },
  labelPosition: {
    type: String,
    default: "right"
  }
});
const emit = defineEmits(["update:modelValue"]);

const { proxy } = getCurrentInstance();
const rules = ref({});

const _value = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
});
const validate = call => {
  let success = true;
  proxy.$refs.previewForm.validate(valid => {
    success = valid;
    call(success);
  });
};
const initDefaultValue = formItem => {
  let value = "";
  ["TextInput", "TextareaInput", "DateTime", "SelectInput"].includes(formItem.name) && (value = "");
  formItem.name === "EditorInput" && (value = `<p>${value}</p>`);
  ["NumberInput"].includes(formItem.name) && (value = 0);
  ["MultipleSelect", "CascaderInput", "ImageUpload", "FileUpload", "UserPicker"].includes(formItem.name) && (value = []);
  return value;
};
const loadFormConfig = forms => {
  forms.forEach(item => {
    const value = props.modelValue[item.id] || initDefaultValue(item);
    _value.value[item.id] = item.name === "NumberInput" ? parseFloat(value) : value;
    if (item.props.required) {
      rules.value[item.id] = [
        {
          type: getValidType(item),
          required: true,
          message: item.props.validateFailMessage || `请填写${item.title}`,
          trigger: item.props.validateTrigger || "blur"
        }
      ];
    }
  });
  console.log(rules.value, "<<<<校验");
};

const getValidType = item => {
  switch (item.valueType) {
    case "Array":
    case "User":
    case "Dept":
      return "array";
    case "String":
    case "Date":
      return "string";
    case "Number":
      return "number";
    default:
      return item.valueType;
  }
};

const submitForm = call => {
  validate(call);
};
const resetForm = async callBack => {
  await nextTick();
  proxy.$refs.previewForm?.resetFields();
  callBack && callBack();
};

defineExpose({
  submitForm,
  resetForm
});

loadFormConfig(props.forms);
</script>

<style lang="less" scoped>
.process-form {
  :deep(.el-form-item__content) {
    > div {
      width: 100%;
    }
  }
}
</style>
